package com.zhouyou.http.view;

import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.IDialog;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.multimodalinput.event.KeyEvent;

public class CancelableDialog extends CommonDialog {
    private static final String TAG = "MonthFragment";
    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.DEBUG, 1234567, TAG);

    public interface OnCancelListener {
        void onCancel(IDialog dialog);
    }

    public interface OnDismissListener {
        void onDismiss(IDialog dialog);
    }

    private OnCancelListener onCancelListener;
    private OnDismissListener onDismissListener;
    private boolean cancelable = true;
    protected Context context;

    public CancelableDialog(Context context) {
        super(context);
        this.context = context;
        super.setDestroyedListener(() -> {
            if (onDismissListener != null) {
                onDismissListener.onDismiss(this);
            }
        });
    }

    @Override
    public boolean clickKeyUp(KeyEvent event) {
        HiLog.warn(LABEL, "### CancelableDialog clickKeyUp");
        int keyCode = event.getKeyCode();
        if (keyCode == KeyEvent.KEY_BACK) {
            HiLog.warn(LABEL, "### CancelableDialog KEY_BACK");
            if (cancelable) {
                cancel();
            } else {
                return true;
            }
        }
        return super.clickKeyUp(event);
    }

    public void cancel() {
        HiLog.warn(LABEL, "### CancelableDialog cancel");
        if (onCancelListener != null) {
            onCancelListener.onCancel(this);
        }
        remove();
    }

    public void dismiss() {
        if (onDismissListener != null) {
            onDismissListener.onDismiss(this);
        }
        remove();
    }

    public void setOnCancelListener(OnCancelListener onCancelListener) {
        this.onCancelListener = onCancelListener;
    }

    public void setOnDismissListener(OnDismissListener onDismissListener) {
        this.onDismissListener = onDismissListener;
    }

    public void setCancelable(boolean cancelable) {
        this.cancelable = cancelable;
    }

    public boolean isCancelable() {
        return cancelable;
    }
}